<?php
namespace Maowenke\pay\wechat;
use EasyWeChat\Factory;
use Maowenke\http\Http;
use Maowenke\pay\Other;

trait WechatOther
{
    use Other;
    /**
     * 微信小程序使用code换取openid
     * @param string $code 授权code
     * @return false|mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    protected function AppletWecateCodeGetOpenid(string $code){
        $config = $this->config;
        $config['response_type'] = 'array';
        $config['log'] = [
            'level' => 'debug',
            'file' => __DIR__.'/wechat.log',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->auth->session($code);
        if(!is_array($response)){
            $response = json_decode($response,true);
        }
        if(isset($response['openid'])&&$response['openid']){
            return $response['openid'];
        }
        $this->message = empty($response['return_msg'])?"获取用户openid失败":$response['return_msg'];
        return false;
    }
    /**
     * h5使用code获取openid
     * @param string $code 授权code
     * @return false|mixed
     */
    protected function H5WecateCodeGetOpenid(string $code){
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        //获取openid
        $response = Http::get($url,[
            'appid' => $this->config['app_id'],
            'secret' => $this->config['secret'],
            'code' => $code,
            'grant_type' => 'authorization_code',
        ]);
        if(!is_array($response)){
            $response = json_decode($response,true);
        }
        if(isset($response['openid'])&&$response['openid']){
            return $response['openid'];
        }else{
            $this->message = empty($response['return_msg'])?'获取openid失败':$response['return_msg'];
            return false;
        }
    }
    /**
     * 微信官方支付
     * @param array $data
     * @return false|mixed
     */
    protected function wechatUnify(array $data){
        $data = $this->handleData($data);
        if(isset($data['trade_type'])&&$data['trade_type']){
            $this->trade_type = $data['trade_type'];
        }else{
            $this->trade_type = "JSAPI";
        }
        //使用jsapi下单呢
        if($this->trade_type=='JSAPI'){
            if(empty($data['openid'])&&empty($data['code'])){
                $this->message = "";
                return false;
            }
            //如果没有openid和code
            if(empty($data['openid'])&&!empty($data['code'])){
                //检查数据
                if(!$this->checking(['app_id','secret'])){
                    return false;
                }
                if(!$this->checking(['pay_type'],$data)){
                    return false;
                }
                //h5
                if($data['pay_type']=='wxofficialaccount'){
                    $openid = $this->H5WecateCodeGetOpenid($data['code']);
                }elseif($data['pay_type']=='wxminiprogram'){
                    //小程序
                    $openid = $this->AppletWecateCodeGetOpenid($data['code']);
                }
                if($openid===false){
                    return false;
                }
                $data['openid'] = $openid;
            }
        }
        $isContract = false;
        if(isset($data['isContract'])){
            if(!empty($data['isContract'])){
                $isContract = true;
            }
            unset($data['isContract']);
        }
        if(isset($data['code'])){
            unset($data['code']);
        }
        if(isset($data['pay_type'])){
            unset($data['pay_type']);
        }
        //通过easywecate支付
        $result = $this->PayObj->order->unify($data,$isContract);
        //判断返回是否有问题
        if(!empty($result['errcode'])||!empty($result['err_code'])||(!empty($result['return_code'])&&$result['return_code']=='FAIL')){
            $message = empty($result['err_code_des'])?null:$result['err_code_des'];
            $message = empty($message)?(empty($result['return_msg'])?null:$result['return_msg']):$message;
            $message = empty($message)?(empty($result['errmsg'])?null:$result['errmsg']):$message;
            $this->message  = empty($message)?"未返回信息":$message;
            return false;
        }
        //根据不同的trade_type分会不同的数据
        if ($this->trade_type=='MWEB'){
            $res = $result;
        }else{
            $res = $this->PayObj->jssdk->bridgeConfig($result['prepay_id']);
            if(!is_array($res)){
                $res = json_decode($res,true);
            }
        }
        return $res;
    }

    /**
     * 处理支付数据
     * @param array $data 待处理数据
     * @return array
     */
    protected function handleData(array $data){
        if(isset($data['total_fee'])){
            $data['total_fee'] = intval($data['total_fee']*100);
        }
        return $data;
    }
}